package com.alibaba.yinan.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.*;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PoiTlTemplateGenerator {

    /**
     * 生成 Word 报告（使用 InputStream 作为模板输入）
     *
     * @param templateStream 模板输入流（从 classpath 或其他来源加载）
     * @param outputPath     输出文件路径，如 "output/report.docx"
     */
    public void generateReport(InputStream templateStream, String outputPath) throws Exception {

        // 1. 准备数据
        Map<String, Object> data = new HashMap<>();
        data.put("title", "实验室月度报告");
        data.put("reportNo", "RPT-2025-001");
        data.put("date", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        data.put("author", "张三");
        data.put("description", "本报告总结了2025年1月份实验室的运行情况，包括设备使用统计、耗材消耗情况等。通过数据分析，发现设备利用率较上月提升15%，整体运行良好。");
        data.put("summary", "综上所述，本月实验室运行平稳，各项指标正常。建议下月继续保持良好态势，并关注设备维护周期。");

        // 2. 图片资源（从 classpath 加载）
        ClassPathResource chartRes = new ClassPathResource("images/chart.png");
        PictureRenderData chartPicture = Pictures.ofStream(chartRes.getInputStream(), PictureType.PNG)
                .size(500, 300)
                .create();
        data.put("chart", chartPicture);

        ClassPathResource photoRes = new ClassPathResource("images/photo.jpg");

        PictureRenderData photo = Pictures.ofStream(photoRes.getInputStream(), PictureType.JPEG)
                .size(400, 300)
                .create();
        data.put("photo", photo);

        // 3. 表格数据
        List<TableRowData> tableData = Arrays.asList(
                new TableRowData("001", "试剂A", 100, "mL", "正常"),
                new TableRowData("002", "试剂B", 250, "mL", "库存充足"),
                new TableRowData("003", "器皿C", 50, "个", "需补充"),
                new TableRowData("004", "耗材D", 1000, "片", "正常"),
                new TableRowData("005", "设备E", 5, "台", "运行中")
        );

        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();

        // 4. 表格循环策略
        Configure config = Configure.builder()
                .bind("dataList", policy).build();

        data.put("dataList", tableData);

        // 5. 渲染模板
        XWPFTemplate template = XWPFTemplate.compile(templateStream, config).render(data);

        // 6. 输出文件
        File outDir = new File("output");
        if (!outDir.exists()) {
            outDir.mkdirs();
        }

        try (FileOutputStream out = new FileOutputStream(outputPath)) {
            template.write(out);
        }
        template.close();

        System.out.println("Word报告生成成功：" + outputPath);
    }
}
